package com.mall.xiaomi.service.impl;

import com.mall.xiaomi.exception.ExceptionEnum;
import com.mall.xiaomi.exception.XmException;
import com.mall.xiaomi.mapper.LoginMapper;
import com.mall.xiaomi.pojo.User;
import com.mall.xiaomi.service.LoginService;
import com.mall.xiaomi.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author mahaoqi
 * @ClassName LoginServiceImpl
 * @Description TODO
 * @Date 2021/2/25 14:26
 * @Version 1.0
 **/
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    /*
     * @Author mahaoqi
     * @Description 登录
     * @Date 2021/2/25 16:44
     * @Param [user]
     * @return com.mall.xiaomi.pojo.User
     **/
    @Override
    public User login(User user) {
        user.setPassword(MD5Util.MD5Encode(user.getPassword()+"","UTF-8"));
        User resultUser = loginMapper.selectOne(user);
        if(resultUser != null){
            return resultUser;
        }
        throw new XmException(ExceptionEnum.GET_USER_NOT_FOUND);
    }




    /*
     * @Author mahaoqi
     * @Description 注册
     * @Date 2021/2/26 10:23
     * @Param [user]
     * @return void
     **/
    @Override
    public void register(User user) {
        User resultUser = new User();
        resultUser.setUsername(user.getUsername());
        //判断用户名是否存在
        if(loginMapper.selectCount(resultUser)==1){
            // 用户名已存在
            throw new XmException(ExceptionEnum.SAVE_USER_REUSE);
        }
        user.setPassword(MD5Util.MD5Encode(user.getPassword()+"","UTF-8"));

        try {
            loginMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new XmException(ExceptionEnum.SAVE_USER_ERROR);
        }
    }


    /*
     * @Author mahaoqi
     * @Description 判断用户名是否存在
     * @Date 2021/2/26 10:26
     * @Param [username]
     * @return void
     **/
    @Override
    public void isUsername(String username) {
        User resultUser = new User();
        resultUser.setUsername(username);
        //判断用户名是否存在
        if(loginMapper.selectCount(resultUser)==1){
            // 用户名已存在
            throw new XmException(ExceptionEnum.SAVE_USER_REUSE);
        }
    }
}
